package com.allinpay.merchantweb.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.allinpay.merchantweb.common.utils.BuildTree;
import com.allinpay.merchantweb.common.utils.SequenceUtil;
import com.allinpay.merchantweb.constants.ReturnCodeConstants;
import com.allinpay.merchantweb.model.CommPrivilegeInfo;
import com.allinpay.merchantweb.model.CommRoleInfo;
import com.allinpay.merchantweb.model.CommRolePrivilege;
import com.allinpay.merchantweb.model.CommUserRole;
import com.allinpay.merchantweb.model.PageForBootStrap;
import com.allinpay.merchantweb.model.PageForLayui;
import com.allinpay.merchantweb.model.Tree;
import com.allinpay.merchantweb.request.AddRoleInfoRequest;
import com.allinpay.merchantweb.request.CommonReqBean;
import com.allinpay.merchantweb.response.AppCommonResponse;
import com.allinpay.merchantweb.response.ResponseData;
import com.allinpay.merchantweb.service.ICommPrivilegeService;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;

@Service
public class CommPrivilegeServiceImpl implements ICommPrivilegeService{
	

	@Autowired
	RestRequestService restRequestService;
	
	@Override
	public Object getPrivilegesByAccount(String userAccount) throws Exception {
		// TODO Auto-generated method stub
		Map<String, String>  reqMap = new HashMap<String, String>();
		reqMap.put("userAccount", userAccount);
		CommonReqBean reqBean = new CommonReqBean(); 
		reqBean.setBizContent(reqMap);
		reqBean.setReqSsn(SequenceUtil.getAppReqSsn());
		
		
		AppCommonResponse<ResponseData<CommPrivilegeInfo>> respBean = restRequestService.postToAppForSingleByObj
				("/privilege/getPrivilegesByAccount"
						, reqBean
						, new TypeToken<AppCommonResponse<ResponseData<CommPrivilegeInfo>>>() {}.getType());
		if( respBean != null) {
			return respBean.getData();
		}
		return null;
	}

	@Override
	public Object queryCompPrivilege() throws Exception {
		// TODO Auto-generated method stub
//		Map<String, String>  reqMap = new HashMap<String, String>();
//		reqMap.put("userAccount", userAccount);
		CommonReqBean reqBean = new CommonReqBean(); 
		reqBean.setReqSsn(SequenceUtil.getAppReqSsn());
//		reqBean.setBizContent(reqMap);
		
		
		AppCommonResponse<ResponseData<CommPrivilegeInfo>> respBean = restRequestService.postToAppForSingleByObj
				("/privilege/queryCompPrivilege", reqBean
						, new TypeToken<AppCommonResponse<ResponseData<CommPrivilegeInfo>>>() {}.getType() );
		if( respBean != null) {
			return getSysMenuTree(respBean.getData().getDataList());
		}
		return null;
	}

	@Override
	public Object queryAllinpayPrivilege() throws Exception {
		// TODO Auto-generated method stub
//		Map<String, String>  reqMap = new HashMap<String, String>();
//		reqMap.put("userAccount", userAccount);
		CommonReqBean reqBean = new CommonReqBean(); 
		reqBean.setReqSsn(SequenceUtil.getAppReqSsn());
//		reqBean.setBizContent(reqMap);
		
		
		AppCommonResponse<ResponseData<CommPrivilegeInfo>> respBean = restRequestService.postToAppForSingleByObj
				("/privilege/queryAllinpayPrivilege", reqBean
						, new TypeToken<AppCommonResponse<ResponseData<CommPrivilegeInfo>>>() {}.getType());
		if( respBean != null) {
			return getSysMenuTree(respBean.getData().getDataList());
		}
		return null;
	}

	@Override
	public boolean checkRoleNameExist(String roleName) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean checkHasSuperAdminRole(String instanceId) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean addRoleInfo(CommRoleInfo roleInfo) throws Exception {
		// TODO Auto-generated method stub
		AddRoleInfoRequest addRoleInfoRequest = new AddRoleInfoRequest(); 
		//一个用户的权限一般在48以内（先申请空间）
		List<CommRolePrivilege> privilegeList = new ArrayList<CommRolePrivilege>(48);
		addRoleInfoRequest.setRoleInfo(roleInfo);
		addRoleInfoRequest.setPrivilegeList(privilegeList);
		
		if( roleInfo.getPrivilegeIds() != null ) {
			for( Integer privilgeId : roleInfo.getPrivilegeIds()) {
				if( privilgeId == -1) {
					continue;
				}
				CommRolePrivilege privilegeTmp = new CommRolePrivilege();
				privilegeTmp.setPrivilegeId(privilgeId);
				privilegeList.add(privilegeTmp);
			}
		}
		
		addRoleInfoRequest.setPrivilegeList(privilegeList);
		
		
		CommonReqBean<AddRoleInfoRequest> reqBean = new CommonReqBean<AddRoleInfoRequest>(); 
		reqBean.setReqSsn(SequenceUtil.getAppReqSsn());
		
		reqBean.setBizContent(addRoleInfoRequest);
		
		AppCommonResponse respBean = restRequestService.postToAppForSingleByObj
				("/privilege/addRoleInfo", reqBean);
		if( respBean != null) {
			if ( !respBean.getState() ) {
				throw new Exception(respBean.getSubMsg());
			}
		}
		
		
		return true;
	}
	
	@Override
	public boolean updateRoleInfo(CommRoleInfo roleInfo) throws Exception {
		// TODO Auto-generated method stub
		AddRoleInfoRequest addRoleInfoRequest = new AddRoleInfoRequest(); 
		//一个用户的权限一般在48以内（先申请空间）
		List<CommRolePrivilege> privilegeList = new ArrayList<CommRolePrivilege>(48);
		addRoleInfoRequest.setRoleInfo(roleInfo);
		addRoleInfoRequest.setPrivilegeList(privilegeList);
		
		if( roleInfo.getPrivilegeIds() != null ) {
			for( Integer privilgeId : roleInfo.getPrivilegeIds()) {
				if( privilgeId == -1) {
					continue;
				}
				CommRolePrivilege privilegeTmp = new CommRolePrivilege();
				privilegeTmp.setPrivilegeId(privilgeId);
				privilegeList.add(privilegeTmp);
			}
		}
		
		addRoleInfoRequest.setPrivilegeList(privilegeList);
		
		
		CommonReqBean<AddRoleInfoRequest> reqBean = new CommonReqBean<AddRoleInfoRequest>(); 
		reqBean.setReqSsn(SequenceUtil.getAppReqSsn());
		
		reqBean.setBizContent(addRoleInfoRequest);
		
		AppCommonResponse respBean = restRequestService.postToAppForSingleByObj
				("/privilege/updateRoleInfo", reqBean);
		if( respBean != null) {
			if ( !respBean.getState() ) {
				throw new Exception(respBean.getSubMsg());
			}
		}
		
		
		return true;
	}
	
	
	@Override
	public boolean batchDeleteRoleInfo(List<Integer> roleIdList) throws Exception {
		// TODO Auto-generated method stub
		

		
		
		CommonReqBean<List<Integer>> reqBean = new CommonReqBean<List<Integer>>(); 
		reqBean.setReqSsn(SequenceUtil.getAppReqSsn());
		
		reqBean.setBizContent(roleIdList);
		
		AppCommonResponse respBean = restRequestService.postToAppForSingleByObj
				("/privilege/batchDeleteRoleInfo", reqBean);
		if( respBean != null) {
			if ( !respBean.getState() ) {
				throw new Exception(respBean.getSubMsg());
			}
		}
		
		
		return true;
	}
	

	@Override
	public boolean updateRoleInfo(CommRoleInfo roleInfo, List<CommRolePrivilege> privilegeList) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean delteRoleInfo(CommRoleInfo roleInfo) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Object queryUserRoleList(CommUserRole commUesrRole) throws Exception {
		// TODO Auto-generated method stub
		
		CommonReqBean<CommUserRole> reqBean = new CommonReqBean<CommUserRole>(); 
		reqBean.setReqSsn(SequenceUtil.getAppReqSsn());
		
		reqBean.setBizContent(commUesrRole);
		
		AppCommonResponse respBean = restRequestService.postToAppForSingleByObj
				("/privilege/queryUserRoleList", reqBean);
		if( respBean != null &&  respBean.getSubCode() != null 
				&& respBean.getSubCode().equals(ReturnCodeConstants.SUB_CODE_SUCC) ) {
			return respBean.getData();
		}else {			
				throw new Exception(respBean.getSubMsg());
		}
	}
	
	@Override
	public ResponseData<CommRoleInfo> queryRoleInfoList(CommRoleInfo commRoleInfo) throws Exception {
		// TODO Auto-generated method stub
		
		CommonReqBean<CommRoleInfo> reqBean = new CommonReqBean<CommRoleInfo>(); 
		reqBean.setReqSsn(SequenceUtil.getAppReqSsn());
		
		reqBean.setBizContent(commRoleInfo);
		
		AppCommonResponse<ResponseData<CommRoleInfo>> respBean = restRequestService.postToAppForSingleByObj
				("/privilege/queryRoleInfoList", reqBean
						,new TypeToken<AppCommonResponse<ResponseData<CommRoleInfo>>>() {}.getType()
						);
		
		if( respBean != null &&  respBean.getSubCode() != null 
				&& respBean.getSubCode().equals(ReturnCodeConstants.SUB_CODE_SUCC) ) {
			return respBean.getData();
		}else {			
				throw new Exception(respBean.getSubMsg());
		}

		
	}
	


	@Override
	public Object queryRolePrivilegeList(CommRolePrivilege commRolePrivilege) throws Exception {
		// TODO Auto-generated method stub
		CommonReqBean<CommRolePrivilege> reqBean = new CommonReqBean<CommRolePrivilege>(); 
		reqBean.setReqSsn(SequenceUtil.getAppReqSsn());
		
		reqBean.setBizContent(commRolePrivilege);
		
		AppCommonResponse<ResponseData<CommRolePrivilege>> respBean = restRequestService.postToAppForSingleByObj
				("/privilege/queryRolePrivilegeList", reqBean
						,new TypeToken<AppCommonResponse<ResponseData<CommRolePrivilege>>>() {}.getType()
						);
		if( respBean != null) {
//			if ( respBean.getState() ) {
//				throw new Exception(respBean.getSubMsg());
//			}
		}
		
		
		CommonReqBean<CommPrivilegeInfo> reqMenuBean = new CommonReqBean<CommPrivilegeInfo>(); 
		reqMenuBean.setReqSsn(SequenceUtil.getAppReqSsn());
		CommPrivilegeInfo commPrivilegeInfo = new CommPrivilegeInfo();
		reqMenuBean.setBizContent(commPrivilegeInfo);

		AppCommonResponse<ResponseData<CommPrivilegeInfo>> respMenuBean = null;
		
		//manger of merchant
		if( commRolePrivilege.getRoleType() == 2 || commRolePrivilege.getRoleType() == 1) {
			respMenuBean = restRequestService.postToAppForSingleByObj
					("/privilege/queryCompPrivilege", reqMenuBean
							, new TypeToken<AppCommonResponse<ResponseData<CommPrivilegeInfo>>>() {}.getType());
		}else if( commRolePrivilege.getRoleType() == 3 ) { //manager of allinpay
			respMenuBean = restRequestService.postToAppForSingleByObj
					("/privilege/queryAllinpayPrivilege", reqMenuBean
							, new TypeToken<AppCommonResponse<ResponseData<CommPrivilegeInfo>>>() {}.getType());
		}
		
		
		
		
		return getCheckedSysMenuTree(respMenuBean.getData().getDataList(), respBean.getData().getDataList());
	}
	
	
	/**
	 * 添加角色树状菜单
	 * @param
	 * @return 树形菜单
	 */
	public Tree<CommPrivilegeInfo> getSysMenuTree(List<CommPrivilegeInfo> commprivilegeList) {
		List<Tree<CommPrivilegeInfo>> trees = new ArrayList<Tree<CommPrivilegeInfo>>();
		for (CommPrivilegeInfo sysMenuDO : commprivilegeList) {
			Tree<CommPrivilegeInfo> tree = new Tree<CommPrivilegeInfo>();
			tree.setId(sysMenuDO.getId().toString());
			tree.setParentId(sysMenuDO.getFatherPowerId().toString());
			tree.setText(sysMenuDO.getPowerName());
			Map<String, Object> attributes = new HashMap<>(16);
//			attributes.put("url", sysMenuDO.getUrl());
//			attributes.put("icon", sysMenuDO.getIcon());
			tree.setAttributes(attributes);
			trees.add(tree);
		}
		// 默认顶级菜单为０，根据数据库实际情况调整
		Tree<CommPrivilegeInfo> t = BuildTree.build(trees);
		return t;
	}
	
	/**
	 * 福利工资卡首页树状菜单
	 * @param
	 * @return 树形菜单
	 */
	public List<Tree<CommPrivilegeInfo>> getEntryMenuTree(List<CommPrivilegeInfo> commprivilegeList) {
		List<Tree<CommPrivilegeInfo>> trees = new ArrayList<Tree<CommPrivilegeInfo>>();
		for (CommPrivilegeInfo sysMenuDO : commprivilegeList) {
			Tree<CommPrivilegeInfo> tree = new Tree<CommPrivilegeInfo>();
			tree.setId(sysMenuDO.getId().toString());
			tree.setParentId(sysMenuDO.getFatherPowerId().toString());
			tree.setTitle(sysMenuDO.getPowerName());
			tree.setHref(sysMenuDO.getPowerUrlNew());
			Map<String, Object> attributes = new HashMap<>(16);
//			attributes.put("url", sysMenuDO.getUrl());
//			attributes.put("icon", sysMenuDO.getIcon());
			tree.setAttributes(attributes);
			trees.add(tree);
		}
		// 默认顶级菜单为０，根据数据库实际情况调整
		List<Tree<CommPrivilegeInfo>> t = BuildTree.buildMenu(trees);
		return t;
	}
	
	
	
	/**
	 * @param
	 * @return 已勾选的树形菜单
	 */
	public Tree<CommPrivilegeInfo> getCheckedSysMenuTree(List<CommPrivilegeInfo> commprivilegeList, List<CommRolePrivilege> rolePrivilegeList) {
		List<Tree<CommPrivilegeInfo>> trees = new ArrayList<Tree<CommPrivilegeInfo>>();
		
		List<Integer> idList = listPriviegeIds(rolePrivilegeList);
		
//		System.out.println("idList:" + idList);
		List<Integer> temp = idList;
		for (CommPrivilegeInfo menu : commprivilegeList) {
			if (temp.contains(menu.getFatherPowerId())) {
				idList.remove(menu.getFatherPowerId());
			}
		}
//		System.out.println("idList:" + idList);
		for (CommPrivilegeInfo sysMenuDO : commprivilegeList) {
			Tree<CommPrivilegeInfo> tree = new Tree<CommPrivilegeInfo>();
			tree.setId(sysMenuDO.getId().toString());
			tree.setParentId(sysMenuDO.getFatherPowerId().toString());
			tree.setText(sysMenuDO.getPowerName());
//			Map<String, Object> attributes = new HashMap<>(16);
			Map<String, Object> state = new HashMap<>(16);
//			System.out.println("id:" + sysMenuDO.getId());
			if( idList.contains(sysMenuDO.getId()) ){
				state.put("selected", true);
				
			} else {
				state.put("selected", false);
			}
			tree.setState(state);
//			tree.setAttributes(attributes);
			trees.add(tree);
		}
		// 默认顶级菜单为０，根据数据库实际情况调整
		Tree<CommPrivilegeInfo> t = BuildTree.build(trees);
		return t;
	}
	
	public List<Integer> listPriviegeIds( List<CommRolePrivilege> rolePrivilegeList) {
		List<Integer> idList  =  new ArrayList<Integer>(32);
		for( CommRolePrivilege eBean : rolePrivilegeList) {
			idList.add(eBean.getPrivilegeId());
		}
		
		return idList;
	}

	@Override
	public Object getEntryMenuTreeByAccount(String userAccount) throws Exception {
		// TODO Auto-generated method stub
		Map<String, String>  reqMap = new HashMap<String, String>();
		reqMap.put("userAccount", userAccount);
		CommonReqBean reqBean = new CommonReqBean(); 
		reqBean.setBizContent(reqMap);
		reqBean.setReqSsn(SequenceUtil.getAppReqSsn());
		
		
		AppCommonResponse<ResponseData<CommPrivilegeInfo>> respBean = restRequestService.postToAppForSingleByObj
				("/privilege/getPrivilegesByAccount"
						, reqBean
						, new TypeToken<AppCommonResponse<ResponseData<CommPrivilegeInfo>>>() {}.getType());
		if( respBean != null) {
			return getEntryMenuTree(respBean.getData().getDataList());
		}
		return null;
	}








	

}
